﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using RecipeBookBusiness;

namespace RecipeBookWeb
{
    public partial class AddRecipe : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //Populate the Ingredient drop down
                IngredientDropDown.DataTextField = "Description";
                IngredientDropDown.DataValueField = "ID";
                repopulateIngredients();

                //Populate the Equipment drop down
                EquipmentDropDown.DataTextField = "Description";
                EquipmentDropDown.DataValueField = "ID";
                repopulateEquipment();

                CategoryDropDown.DataTextField = "Name";
                CategoryDropDown.DataValueField = "ID";
                repopulateCategories();

                //Initialize grid view data sources
                IngredientGridView.DataSource = IngredientList;
                IngredientGridView.DataBind();
                EquipmentGridView.DataSource = EquipmentList;
                EquipmentGridView.DataBind();
                CategoryGridView.DataSource = CategoryList;
                CategoryGridView.DataBind();
            }
        }

        /// <summary>
        /// Adds an ingredient row to the form.
        /// </summary>
        /// <param name="sender">the add button</param>
        /// <param name="e">event arguments</param>
        protected void AddIngredient(object sender, EventArgs e)
        {
            DataTable newIngredientTable = IngredientList;
            DataRow ingredientRow = newIngredientTable.NewRow();
            ingredientRow["Amount"] = Amount.Text.Trim();
            ingredientRow["Description"] = IngredientDropDown.SelectedItem.Text;
            ingredientRow["ID"] = IngredientDropDown.SelectedValue;
            newIngredientTable.Rows.Add(ingredientRow);
            IngredientList = newIngredientTable;
            IngredientGridView.DataSource = IngredientList;
            IngredientGridView.DataBind();

            Amount.Text = string.Empty;
            repopulateIngredients();
        }

        /// <summary>
        /// Removes an ingredient row from the form.
        /// </summary>
        /// <param name="sender">the X button</param>
        /// <param name="e">event arguments</param>
        protected void RemoveIngredient(object sender, CommandEventArgs e)
        {
            int idToRemove = Convert.ToInt32(e.CommandArgument);
            DataRow drToRemove = null;
            DataTable newIngredientTable = IngredientList;
            foreach (DataRow dr in newIngredientTable.Rows)
            {
                if (dr["ID"].Equals(idToRemove))
                {
                    drToRemove = dr;
                }
            }
            if (drToRemove != null)
            {
                newIngredientTable.Rows.Remove(drToRemove);
            }

            IngredientList = newIngredientTable;
            IngredientGridView.DataSource = IngredientList;
            IngredientGridView.DataBind();

            repopulateIngredients();            
        }

        /// <summary>
        /// Adds an equipment row to the form.
        /// </summary>
        /// <param name="sender">the add button</param>
        /// <param name="e">event arguments</param>
        protected void AddEquipment(object sender, EventArgs e)
        {
            DataTable newEquipmentTable = EquipmentList;
            DataRow equipmentRow = newEquipmentTable.NewRow();
            equipmentRow["Description"] = EquipmentDropDown.SelectedItem.Text;
            equipmentRow["ID"] = EquipmentDropDown.SelectedValue;
            newEquipmentTable.Rows.Add(equipmentRow);

            EquipmentList = newEquipmentTable;
            EquipmentGridView.DataSource = EquipmentList;
            EquipmentGridView.DataBind();

            repopulateEquipment();
        }

        /// <summary>
        /// Removes an equipment row from the form.
        /// </summary>
        /// <param name="sender">the X button</param>
        /// <param name="e">event arguments</param>
        protected void RemoveEquipment(object sender, CommandEventArgs e)
        {
            int idToRemove = Convert.ToInt32(e.CommandArgument);
            DataRow drToRemove = null;
            DataTable newEquipmentTable = EquipmentList;
            foreach (DataRow dr in newEquipmentTable.Rows)
            {
                if (dr["ID"].Equals(idToRemove))
                {
                    drToRemove = dr;
                }
            }
            if (drToRemove != null)
            {
                newEquipmentTable.Rows.Remove(drToRemove);
            }

            EquipmentList = newEquipmentTable;
            EquipmentGridView.DataSource = EquipmentList;
            EquipmentGridView.DataBind();

            repopulateEquipment();
        }

        protected void AddCategory(object sender, EventArgs e)
        {
            DataTable newCategoryTable = CategoryList;
            DataRow categoryRow = newCategoryTable.NewRow();
            categoryRow["Name"] = CategoryDropDown.SelectedItem.Text;
            categoryRow["ID"] = CategoryDropDown.SelectedValue;
            newCategoryTable.Rows.Add(categoryRow);

            CategoryList = newCategoryTable;
            CategoryGridView.DataSource = CategoryList;
            CategoryGridView.DataBind();

            repopulateCategories();
        }

        protected void RemoveCategory(object sender, CommandEventArgs e)
        {
            int idToRemove = Convert.ToInt32(e.CommandArgument);
            DataRow drToRemove = null;
            DataTable newCategoryTable = CategoryList;
            foreach (DataRow dr in newCategoryTable.Rows)
            {
                if (dr["ID"].Equals(idToRemove))
                {
                    drToRemove = dr;
                }
            }
            if (drToRemove != null)
            {
                newCategoryTable.Rows.Remove(drToRemove);
            }

            CategoryList = newCategoryTable;
            CategoryGridView.DataSource = CategoryList;
            CategoryGridView.DataBind();

            repopulateCategories();
        }

        /// <summary>
        /// Adds a new recipe to the database by pulling the data from the forms
        /// and sending the information to the ModelFacade.
        /// </summary>
        /// <param name="sender">the submit button</param>
        /// <param name="e">event arguments</param>
        protected void SubmitRecipe(object sender, EventArgs e)
        {
            bool validated = true;
            int userID = -1;
            if (Session["CurrentUser"] != null)
                userID = ModelFacade.GetUserID(Session["CurrentUser"].ToString());

            if (userID <= 0)
            {
                validated = false;
                ErrorLabel.Text = "Your Session has expired. Please login to add a recipe.<br><br>";
            }

            if (CategoryList.Rows.Count == 0)
            {
                validated = false;
                ErrorLabel.Text = "You must add at least one Category to your Recipe.<br><br>";
            }

            if (IngredientList.Rows.Count == 0)
            {
                validated = false;
                ErrorLabel.Text = "You must add at least one Ingredient to your Recipe.<br><br>";
            }

            if (validated)
            {
                ErrorLabel.Visible = false;
                string submitName = name.Text.Trim();
                int submitSize = Convert.ToInt32(servingSize.Text.Trim());
                string submitNutrition = nutrition.Text;
                string submitInstruction = instructions.Text;

                List<KeyValuePair<int, string>> ingredients = new List<KeyValuePair<int, string>>();
                foreach (DataRow dr in IngredientList.Rows)
                {
                    ingredients.Add(new KeyValuePair<int, string>((int)dr["ID"], dr["Amount"].ToString()));
                }

                List<int> equipmentIDs = new List<int>();
                foreach (DataRow dr in EquipmentList.Rows)
                {
                    equipmentIDs.Add((int)dr["ID"]);
                }

                List<int> categoryIDs = new List<int>();
                foreach (DataRow dr in CategoryList.Rows)
                {
                    categoryIDs.Add((int)dr["ID"]);
                }
                int newID = RecipeBookBusiness.ModelFacade.AddRecipe(submitName, submitSize, userID, submitNutrition, submitInstruction, DateTime.Now, ingredients, equipmentIDs, categoryIDs);

                Response.Redirect("ViewRecipe.aspx?RecipeID=" + newID);
            }
            else
            {
                ErrorLabel.Visible = true;
            }
        }

        private void repopulateCategories()
        {
            List<int> categories = new List<int>();
            foreach (DataRow dr in CategoryList.Rows)
            {
                categories.Add((int)dr["ID"]);
            }
            CategoryDropDown.DataSource = ModelFacade.GetCategoriesExclusive(categories);
            CategoryDropDown.DataBind();
        }

        private void repopulateEquipment()
        {
            List<int> equipment = new List<int>();
            foreach (DataRow dr in EquipmentList.Rows)
            {
                equipment.Add((int)dr["ID"]);
            }
            EquipmentDropDown.DataSource = ModelFacade.GetEquipmentExclusive(equipment);
            EquipmentDropDown.DataBind();
        }

        private void repopulateIngredients()
        {
            List<int> ingredients = new List<int>();
            foreach (DataRow dr in IngredientList.Rows)
            {
                ingredients.Add((int)dr["ID"]);
            }
            IngredientDropDown.DataSource = ModelFacade.GetIngredientsExclusive(ingredients);
            IngredientDropDown.DataBind();
        }

        private DataTable CategoryList
        {
            get
            {
                if (ViewState["CategoryList"] == null)
                {
                    //Initialize our category list
                    DataTable categoryList = new DataTable();
                    categoryList.Columns.Add("Name", typeof(string));
                    categoryList.Columns.Add("ID", typeof(int));
                    ViewState["CategoryList"] = categoryList;
                }
                return (DataTable)ViewState["CategoryList"];
            }
            set
            {
                ViewState["CategoryList"] = value;
            }
        }

        private DataTable EquipmentList
        {
            get
            {
                if (ViewState["EquipmentList"] == null)
                {
                    //Initialize our equipment list
                    DataTable equipmentList = new DataTable();
                    equipmentList.Columns.Add("Description", typeof(string));
                    equipmentList.Columns.Add("ID", typeof(int));
                    ViewState["EquipmentList"] = equipmentList;
                }
                return (DataTable)ViewState["EquipmentList"];
            }
            set
            {
                ViewState["EquipmentList"] = value;
            }
        }

        private DataTable IngredientList
        {
            get
            {
                if (ViewState["IngredientList"] == null)
                {
                    //Initialize our ingredient list
                    DataTable ingredientList = new DataTable();
                    ingredientList.Columns.Add("Amount", typeof(string));
                    ingredientList.Columns.Add("Description", typeof(string));
                    ingredientList.Columns.Add("ID", typeof(int));
                    ViewState["IngredientList"] = ingredientList;
                }
                return (DataTable)ViewState["IngredientList"];
            }
            set
            {
                ViewState["IngredientList"] = value;
            }
        }
    }
}
